/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package org.myontology.users;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.myontology.controller.AbstractAction;
import org.myontology.controller.AttributeHolder;
import org.myontology.controller.WebAttributeHolder;
import org.myontology.view.items.FormBuilderStates;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchResponse;

public class OpenIDVerify extends AbstractAction {

	private Logger logger;
	
	public void execute(AttributeHolder attributes) throws Exception {
		if (attributes instanceof WebAttributeHolder) {
			WebAttributeHolder web = (WebAttributeHolder) attributes;
			HttpServletRequest request = web.getRequest();

			ParameterList response = new ParameterList(request.getParameterMap());

			DiscoveryInformation discovered = OpenIDLogin.DISCOVERY_INFORMATION.getValue(attributes);

			// extract the receiving URL from the HTTP request
            StringBuffer receivingURL = request.getRequestURL();

            String queryString = request.getQueryString();

            ConsumerManager manager = OpenIDLogin.CONSUMER_MANAGER.getValue(attributes);
            if (queryString != null && queryString.length() > 0)
                receivingURL.append("?").append(request.getQueryString());

            // verify the response; ConsumerManager needs to be the same
            // (static) instance used to place the authentication request
            VerificationResult verification = manager.verify(
                    receivingURL.toString(),
                    response, discovered);

            // examine the verification result and extract the verified identifier
            Identifier verified = verification.getVerifiedId();

            User user = new User();
    		UserProtocol.USER.setValue(attributes, user);
    		UserProtocol.TITLE.setValue(attributes, "Create new OpenID - User");
    		UserProtocol.EXISTING.setValue(attributes, false);
    		UserProtocol.STATE.setValue(attributes, FormBuilderStates.CREATE);

			user.setValue(discovered.getClaimedIdentifier().getIdentifier());
            if (verified != null)
            {

                AuthSuccess authSuccess =
                        (AuthSuccess) verification.getAuthResponse();

                if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX))
                {

                    FetchResponse fetchResp = (FetchResponse) authSuccess
                            .getExtension(AxMessage.OPENID_NS_AX);

                   
            		user.email.addValue(fetchAttribute(fetchResp,"Email"));
//            		user.firstName.addValue(fetchAttribute(fetchResp,"FirstName"));
//            		user.lastName.addValue(fetchAttribute(fetchResp,"LastName"));
                }
                
                
            }

		}
		else {
			logger.error("OpenIdVerification works only with web requests!!");
		}

	}

	/**
	 * @param fetchResp
	 * @return
	 */
	private String fetchAttribute(FetchResponse fetchResp,String key) {
		List emails = fetchResp.getAttributeValues(key);
		String email = emails==null?"":(String) emails.get(0);

		return email;
	}

}
